// ignore_for_file: file_names

part of common_lib_plugin;

class ImageUtil {
  static Future<ui.Image> loadImageByProvider(
    ImageProvider provider, {
    ImageConfiguration config = ImageConfiguration.empty,
  }) async {
    Completer<ui.Image> completer = Completer<ui.Image>(); //完成的回调
    late ImageStreamListener listener;
    ImageStream stream = provider.resolve(config); //获取图片流
    listener = ImageStreamListener((ImageInfo frame, bool sync) {
      //监听
      final ui.Image image = frame.image;
      completer.complete(image); //完成
      stream.removeListener(listener); //移除监听
    });
    stream.addListener(listener); //添加监听
    return completer.future; //返回
  }

  /// 返回Image的展示高度
  static Future<Size> getImageDisplayHeight(
    String imageUrl, {
    ImageConfiguration config = ImageConfiguration.empty,
  }) async {
    final Completer<Size> result = Completer<Size>();
    if (imageUrl.isNotNull) {
      ImageProvider provider = CachedNetworkImageProvider(imageUrl);
      provider.resolve(config).addListener(ImageStreamListener((ImageInfo info, bool _) {
        final width = info.image.width;
        final height = info.image.height;
        if (width > 0 && height > 0) {
          result.complete(Size(width.toDouble(), height.toDouble()));
        } else {
          result.complete(Size.zero);
        }
      }));
    } else {
      result.complete(Size.zero);
    }
    return result.future;
  }
}
